#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const inquirer = require("inquirer");
const ejs = require("ejs");

inquirer
  .prompt([
    {
      type: "input",
      name: "name",
      message: "Your project name is ?"
    },
    {
      type: "input",
      name: "age",
      message: "Your age is ?"
    }
  ])
  .then(answers => {
    // 模板目录
    const tmplDir = path.join(__dirname, "templates");
    // 目标目录，命令行在哪个目录执行就是哪个目录
    const destDir = process.cwd();

    // 读取模板文件转换到目标目录
    fs.readdir(tmplDir, (err, files) => {
      if (err) throw err;
      files.forEach(file => {
        // 通过模板引擎渲染（这里是相对路径）
        ejs.renderFile(path.join(tmplDir, file), answers, (err, result) => {
          if (err) throw err;
          // 写入到目标路径
          fs.writeFileSync(path.join(destDir, file), result);
        });
      });
    });
  });
